package com.le.tester.imooc.oldfairy.test;

import java.util.LinkedList;
import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2023/6/3 14:43
 * description：simple product customer
 */
public class ProducerCustomerModel {

    //队列中生产的最大值
    private final static int MAX = 10;
    private LinkedList<Integer> queue = new LinkedList<>();


    private ReentrantLock lock = new ReentrantLock();

    //对于生产者和消费者的判定条件，使用lock中的newCondition()
    private Condition full = lock.newCondition();
    private Condition empty = lock.newCondition();


    int readData() throws InterruptedException {
        Thread.sleep((long) (Math.random() * 1000));
        return (int) Math.floor(Math.random());
    }

    //product
    public void readDB() throws InterruptedException {
        lock.lock();

        //队列已满
        if (Objects.equals(MAX, queue.size())) {
            full.await();
            return;
        }

        int data = readData();
        //被消费只有剩下一个的时候，进行了唤醒
        if (Objects.equals(1, queue.size())) {
            empty.signalAll();
        }

        queue.add(data);
        lock.unlock();
    }

    //customer
    public void calculate() throws InterruptedException {
        lock.lock();
        if (queue.size() == 0) {
            //告知是空
            empty.await();
        }

        Integer data = queue.remove();
        System.out.println("queue-size:" + queue.size());
        if (queue.size() == MAX - 1) {
            full.signalAll();
        }

        data *= 100;
        lock.unlock();

    }

    public static void main(String[] argv) {
        ProducerCustomerModel p = new ProducerCustomerModel();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        p.readDB();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        new Thread(() -> {
            while (true) {
                try {
                    p.calculate();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
